﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using OilDB;

namespace MainApp
{
    public partial class FrmImportPreview : XtraForm
    {
        public FrmImportPreview()
        {
            InitializeComponent();
        }

        DataSet previewImportData = new DataSet();
        DataSet previewCurrData = new DataSet();

        public bool showPreView(DataSetOilManagement currData, DataSet importData, Guid StoreID)
        {
            //Dictionary for translation
            //"Stores", "Companies", "Customers", "Dispensers", "Imports", "Debts", "Sells", "Expenses", "Payments", "Receipts", "Products"
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["Stores"] = "Cây xăng";
            dic["Companies"] = "Khách hàng";
            dic["Customers"] = "Xe";
            dic["Dispensers"] = "Vòi";
            dic["Imports"] = "Nhập xăng";
            dic["Debts"] = "Nợ";
            dic["Sells"] = "Bán xăng";
            dic["Expenses"] = "Chi phí";
            dic["Payments"] = "Trả nợ";
            dic["Receipts"] = "Hóa đơn";
            dic["Products"] = "Loại xăng";
            dic["Note"] = "Ghi chú";
            dic["StoreName"] = "Cây xăng";
            dic["StoreAddress"] = "Địa chỉ";
            dic["Customer"] = "Xe";
            dic["Company"] = "Khách hàng";
            dic["CompanyName"] = "Công ty";
            dic["ADDRESS"] = "Địa chỉ";
            dic["Phone"] = "Điện thoại";
            dic["Mobile"] = "Di động";
            dic["CustomerName"] = "Xe";
            dic["ImportTime"] = "Ngày nhập";
            dic["Amount"] = "Số lượng";
            dic["StoreID"] = "Cây xăng";
            dic["Product"] = "Loại xăng";
            dic["SellTime"] = "Ngày bán";
            dic["Price"] = "Giá bán";
            dic["Commission"] = "Hoa hồng";            
            dic["ExpenseTime"] = "Ngày chi";
            dic["Reason"] = "Lý do";
            dic["PayTime"] = "Ngày trả";
            dic["DebtTime"] = "Ngày nợ";
            dic["Name"] = "Tên";
            dic["Active"] = "Hoạt động";
            dic["Dispenser"] = "Vòi";
            dic["ReceiptNumber"] = "Số hóa đơn";
            dic["TaxCode"] = "Mã số thuế";
            dic["ReceiptTime"] = "Ngày xuất hóa đơn";
            dic["Fee"] = "Lệ phí xăng dầu";

            cbTableList.Items.Clear();
            previewImportData.Tables.Clear();
            previewCurrData.Tables.Clear();
            
            int numberOfRow = 0;
            foreach (DataTable table in importData.Tables)
            {
                numberOfRow += table.Rows.Count;
            }

            FrmProgess frmPgrogress = new FrmProgess();
            frmPgrogress.Title = "Analyze import data";
            frmPgrogress.ProgressMin = 0;
            frmPgrogress.ProgressMax = numberOfRow;
            frmPgrogress.Show();
            foreach (DataTable table in importData.Tables)
            {
                if (table.TableName.EndsWith("DeletedRows"))
                {
                    continue;
                }

                frmPgrogress.Info = "Analyzing " + table.TableName + " ...";
                try
                {

                    #region Building Schema
                    bool isProductList;
                    bool isStores;
                    bool isCustomers;
                    bool isCompanies;
                    DataTable deleteTable = importData.Tables[table.TableName + "DeletedRows"];
                    //cbTableList.Items.Add(table.TableName);
                    cbTableList.Items.Add(new DisplayObj<DataTable>(table, dic[table.TableName]));
                    //2 Datatable, một chưa dữ liệu import, một chứa dữ liệu đang có trong DB
                    DataTable previewImportTable = previewImportData.Tables.Add(table.TableName);
                    DataTable previewCurrTable = previewCurrData.Tables.Add(table.TableName);


                    isProductList = table.TableName == "Products";
                    isStores = table.TableName == "Stores";
                    isCustomers = table.TableName == "Customers";
                    isCompanies = table.TableName == "Companies";


                    foreach (DataColumn col in table.Columns)
                    {
                        DataColumn previewImportcol = new DataColumn();
                        DataColumn previewCurrcol = new DataColumn();
                        previewImportcol.ColumnName = col.ColumnName;
                        previewCurrcol.ColumnName = col.ColumnName;

                        if (dic.ContainsKey(col.ColumnName))
                        {
                            if (col.ColumnName == "Amount" && (table.TableName == "Payments" || table.TableName == "Expenses"))
                            {
                                previewImportcol.Caption = "Số tiền";
                                previewCurrcol.Caption = "Số tiền";
                            }
                            else
                            {
                                previewImportcol.Caption = dic[col.ColumnName];
                                previewCurrcol.Caption = dic[col.ColumnName];
                            }
                        }

                        if ((!isProductList && col.ColumnName == "Product") || (!isStores && col.ColumnName == "StoreID")
                            || (!isCustomers && col.ColumnName == "Customer") || (!isCompanies && col.ColumnName == "Company"))
                        {
                            previewImportcol.DataType = typeof(string);
                            previewCurrcol.DataType = typeof(string);
                        }
                        else if (col.DataType == typeof(DateTime))
                        {
                            previewImportcol.DataType = typeof(string);
                            previewCurrcol.DataType = typeof(string);
                        }
                        else
                        {
                            previewImportcol.DataType = col.DataType;
                            previewCurrcol.DataType = col.DataType;
                        }


                        previewImportTable.Columns.Add(previewImportcol);
                        previewCurrTable.Columns.Add(previewCurrcol);
                    }
                    #endregion


                    DataTable currTable = currData.Tables[table.TableName];
                    object[] keyvalues = new object[currTable.PrimaryKey.Length];
                    DataColumn[] primaryCol = currTable.PrimaryKey;

                    #region Process Insert and Update Rows
                    bool changedRowDiff;
                    List<DataRow> previewImportChangedRows = new List<DataRow>();
                    List<DataRow> previewCurrChangedRows = new List<DataRow>();
                    foreach (DataRow row in table.Rows)
                    {
                        DataRow previewImportRow = previewImportTable.NewRow();
                        DataRow previewCurrRow = previewCurrTable.NewRow();
                        foreach (DataColumn col in table.Columns)
                        {
                            if (col.ColumnName == "Product" && !isProductList)
                            {
                                DataSetOilManagement.ProductsRow productRow = currData.Products.FindByID((Guid)row[col]);
                                if (productRow != null)
                                {
                                    previewImportRow[col.ColumnName] = productRow.ProductName; 
                                }
                            }
                            else if (col.ColumnName == "StoreID" && !isStores)
                            {
                                DataSetOilManagement.StoresRow storeRow = currData.Stores.FindByID((Guid)row[col]);
                                if (storeRow != null)
                                {
                                    previewImportRow[col.ColumnName] = storeRow.StoreName; 
                                }
                            }
                            else if (col.ColumnName == "Customer" && !isCustomers)
                            {
                                DataSetOilManagement.CustomersRow customerRow = currData.Customers.FindByID((Guid)row[col]);
                                if (customerRow != null)
                                {
                                    previewImportRow[col.ColumnName] = customerRow.CustomerName;
                                }
                                else
                                {
                                    DataRow findRow = importData.Tables["Customers"].Rows.Find(row[col]);
                                    if (findRow != null)
                                    {
                                        previewImportRow[col.ColumnName] = findRow["CustomerName"];
                                    }
                                }
                            }
                            else if (col.ColumnName == "Company" && !isCompanies && col.DataType == typeof(Guid))
                            {
                                if (row[col] != DBNull.Value)
                                {
                                    DataSetOilManagement.CompaniesRow comRow = currData.Companies.FindByID((Guid)row[col]);
                                    if (comRow != null)
                                    {
                                        previewImportRow[col.ColumnName] = comRow.CompanyName;
                                    }
                                    else
                                    {
                                        DataRow findRow = importData.Tables["Companies"].Rows.Find(row[col]);
                                        if (findRow != null)
                                        {
                                            previewImportRow[col.ColumnName] = findRow["CompanyName"];
                                        }
                                    }
                                }
                                else 
                                {
                                    previewImportRow[col.ColumnName] = "";
                                }
                            }
                            else if (col.DataType == typeof(DateTime))
                            {
                                previewImportRow[col.ColumnName] = ((DateTime)row[col.ColumnName]).ToString("dd/MM/yyyy");
                            }
                            else
                            {
                                previewImportRow[col.ColumnName] = row[col.ColumnName];
                            }
                        }


                        for (int i = 0; i < keyvalues.Length; i++)
                        {
                            keyvalues[i] = row[primaryCol[i].ColumnName];
                        }

                        DataRow currRow = currTable.Rows.Find(keyvalues);
                        if (currRow != null)
                        {
                            changedRowDiff = false;
                            foreach (DataColumn col in table.Columns)
                            {
                                if (col.ColumnName == "Product" && !isProductList)
                                {
                                    DataSetOilManagement.ProductsRow productRow = currData.Products.FindByID((Guid)currRow[col.ColumnName]);
                                    if (productRow != null)
                                    {
                                        previewCurrRow[col.ColumnName] = productRow.ProductName; 
                                    }
                                }
                                else if (col.ColumnName == "StoreID" && !isStores)
                                {
                                    DataSetOilManagement.StoresRow storeRow = currData.Stores.FindByID((Guid)currRow[col.ColumnName]);
                                    if (storeRow != null)
                                    {
                                        previewCurrRow[col.ColumnName] = storeRow.StoreName; 
                                    }
                                }
                                else if (col.ColumnName == "Customer" && !isCustomers)
                                {
                                    DataSetOilManagement.CustomersRow customerRow = currData.Customers.FindByID((Guid)currRow[col.ColumnName]);
                                    if (customerRow != null)
                                    {
                                        previewCurrRow[col.ColumnName] = customerRow.CustomerName;
                                    }
                                    else
                                    {
                                        DataRow findRow = importData.Tables["Customers"].Rows.Find(currRow[col.ColumnName]);
                                        if (findRow != null)
                                        {
                                            previewCurrRow[col.ColumnName] = findRow["CustomerName"];
                                        }
                                    }

                                }
                                else if (col.ColumnName == "Company" && !isCompanies && col.DataType == typeof(Guid))
                                {
                                    if (currRow[col.ColumnName] != DBNull.Value)
                                    {
                                        DataSetOilManagement.CompaniesRow comRow = currData.Companies.FindByID((Guid)currRow[col.ColumnName]);
                                        if (comRow != null)
                                        {
                                            previewCurrRow[col.ColumnName] = comRow.CompanyName;
                                        }
                                        else
                                        {
                                            DataRow findRow = importData.Tables["Companies"].Rows.Find(currRow[col.ColumnName]);
                                            if (findRow != null)
                                            {
                                                previewCurrRow[col.ColumnName] = findRow["CompanyName"];
                                            }
                                        } 
                                    }
                                    else
                                    {
                                        previewImportRow[col.ColumnName] = "";
                                    }
                                }
                                else if (col.DataType == typeof(DateTime))
                                {
                                    previewCurrRow[col.ColumnName] = ((DateTime)currRow[col.ColumnName]).ToString("dd/MM/yyyy");
                                }
                                else
                                {
                                    previewCurrRow[col.ColumnName] = currRow[col.ColumnName];
                                }


                                if (table.TableName == "Receipts" && col.ColumnName == "Fee")
                                {
                                    //if (!previewCurrRow["Fee"].Equals(previewImportRow["FeePerUnit"]))
                                    //{
                                    //}
                                }
                                else if (!previewCurrRow[col.ColumnName].Equals(previewImportRow[col.ColumnName]))
                                {
                                    changedRowDiff = true;
                                }
                            }

                            if (changedRowDiff)
                            {
                                previewImportChangedRows.Add(previewImportRow);
                                previewCurrChangedRows.Add(previewCurrRow);
                            }
                        }
                        else
                        {
                            previewImportTable.Rows.Add(previewImportRow);
                            previewCurrTable.Rows.Add(previewCurrRow);
                        }

                        frmPgrogress.ProgressCurrent++;
                    }
                    for (int i = 0; i < previewCurrChangedRows.Count; i++)
                    {
                        previewImportTable.Rows.Add(previewImportChangedRows[i]);
                        previewCurrTable.Rows.Add(previewCurrChangedRows[i]);
                    }
                    #endregion

                    #region Process Deleted Rows
                    foreach (DataRow row in deleteTable.Rows)
                    {
                        DataRow previewImportRow = previewImportTable.NewRow();
                        DataRow previewCurrRow = previewCurrTable.NewRow();

                        for (int i = 0; i < keyvalues.Length; i++)
                        {
                            if (primaryCol[i].ColumnName == "StoreID")
                            {
                                keyvalues[i] = StoreID;
                            }
                            else
                            {
                                keyvalues[i] = row[0];
                            }
                        }

                        DataRow currRow = currTable.Rows.Find(keyvalues);
                        if (currRow != null)
                        {
                            foreach (DataColumn col in table.Columns)
                            {
                                if (col.ColumnName == "Product" && !isProductList)
                                {
                                    DataSetOilManagement.ProductsRow productRow = currData.Products.FindByID((Guid)currRow[col.ColumnName]);
                                    if (productRow != null)
                                    {
                                        previewCurrRow[col.ColumnName] = productRow.ProductName; 
                                    }
                                }
                                else if (col.ColumnName == "StoreID" && !isStores)
                                {
                                    DataSetOilManagement.StoresRow storeRow = currData.Stores.FindByID((Guid)currRow[col.ColumnName]);
                                    if (storeRow != null)
                                    {
                                        previewCurrRow[col.ColumnName] = storeRow.StoreName; 
                                    }
                                }
                                else if (col.ColumnName == "Customer" && !isCustomers)
                                {
                                    DataSetOilManagement.CustomersRow customerRow = currData.Customers.FindByID((Guid)currRow[col.ColumnName]);
                                    if (customerRow != null)
                                    {
                                        previewCurrRow[col.ColumnName] = customerRow.CustomerName;
                                    }
                                    else
                                    {
                                        DataRow findRow = importData.Tables["Customers"].Rows.Find(currRow[col.ColumnName]);
                                        if (findRow != null)
                                        {
                                            previewCurrRow[col.ColumnName] = findRow["CustomerName"];
                                        }
                                    }
                                }
                                else if (col.ColumnName == "Company" && !isCompanies && col.DataType==typeof(Guid))
                                {
                                    if (currRow[col.ColumnName] != DBNull.Value)
                                    {
                                        DataSetOilManagement.CompaniesRow comRow = currData.Companies.FindByID((Guid)currRow[col.ColumnName]);
                                        if (comRow != null)
                                        {
                                            previewCurrRow[col.ColumnName] = comRow.CompanyName;
                                        }
                                        else
                                        {
                                            DataRow findRow = importData.Tables["Companies"].Rows.Find(currRow[col.ColumnName]);
                                            if (findRow != null)
                                            {
                                                previewCurrRow[col.ColumnName] = findRow["CompanyName"];
                                            }
                                        } 
                                    }
                                    else
                                    {
                                        previewImportRow[col.ColumnName] = "";
                                    }
                                }
                                else if (col.DataType == typeof(DateTime))
                                {
                                    previewCurrRow[col.ColumnName] = ((DateTime)currRow[col.ColumnName]).ToString("dd/MM/yyyy");
                                }
                                else
                                {
                                    previewCurrRow[col.ColumnName] = currRow[col.ColumnName];
                                }
                            }
                            previewImportTable.Rows.Add(previewImportRow);
                            previewCurrTable.Rows.Add(previewCurrRow);
                            frmPgrogress.ProgressCurrent++;
                        }
                    }
                    #endregion

                }
                finally
                {
                    frmPgrogress.Close();
                }
            }            

            gridControlImportData.DataSource = previewImportData;
            gridControlCurrentData.DataSource = previewCurrData;
            cbTableList.SelectedIndex = 0;
            return this.ShowDialog() == System.Windows.Forms.DialogResult.OK;
        }

        private void cbTableList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbTableList.SelectedItem !=null)
            {
                gridControlImportData.DataMember = ((DisplayObj<DataTable>)cbTableList.SelectedItem).Data.TableName;
                gvImportData.PopulateColumns();
                gvImportData.Columns["ID"].Visible = false;

                foreach (DevExpress.XtraGrid.Columns.GridColumn col in gvImportData.Columns)
                {
                    if (col.FieldName == "Amount")
                    {
                        if (gridControlImportData.DataMember == "Payments" || gridControlImportData.DataMember == "Expenses" || gridControlImportData.DataMember == "Debts")
                        {
                            col.ColumnEdit = MoneyEdit;
                        }
                        else
                        {
                            col.ColumnEdit = AmountEdit;
                        }
                    }
                    else if (col.FieldName == "Price" || col.FieldName == "Commission")
                    {
                        col.ColumnEdit = MoneyEdit;
                    }
                }

                
                gridControlCurrentData.DataMember = ((DisplayObj<DataTable>)cbTableList.SelectedItem).Data.TableName;
                gvCurrentData.PopulateColumns();
                gvCurrentData.Columns["ID"].Visible = false;
            }
        }

        private void FrmImportPreview_Load(object sender, EventArgs e)
        {
            gvImportData.Appearance.FocusedRow.BackColor = gvImportData.Appearance.SelectedRow.BackColor;
            gvImportData.Appearance.FocusedRow.BackColor2 = gvImportData.Appearance.SelectedRow.BackColor2;
            gvImportData.Appearance.HideSelectionRow.BackColor = gvImportData.Appearance.SelectedRow.BackColor;
            gvImportData.Appearance.HideSelectionRow.BackColor2 = gvImportData.Appearance.SelectedRow.BackColor2;

            gvCurrentData.Appearance.FocusedRow.BackColor = gvImportData.Appearance.SelectedRow.BackColor;
            gvCurrentData.Appearance.FocusedRow.BackColor2 = gvImportData.Appearance.SelectedRow.BackColor2;
            gvCurrentData.Appearance.HideSelectionRow.BackColor = gvImportData.Appearance.SelectedRow.BackColor;
            gvCurrentData.Appearance.HideSelectionRow.BackColor2 = gvImportData.Appearance.SelectedRow.BackColor2;
        }

        private void cbHorizontal_CheckStateChanged(object sender, EventArgs e)
        {
            if (cbHorizontal.Checked)
            {
                mainPanel.Orientation = Orientation.Horizontal;
                mainPanel.SplitterDistance = mainPanel.Height / 2;
            }
            else
            {
                mainPanel.Orientation = Orientation.Vertical;
                mainPanel.SplitterDistance = mainPanel.Width / 2;
            }
        }

        private void gvImportData_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gvCurrentData.FocusedRowHandle = e.FocusedRowHandle;
        }

        private void gvCurrentData_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            gvImportData.FocusedRowHandle = e.FocusedRowHandle;
        }

        private void gvImportData_TopRowChanged(object sender, EventArgs e)
        {
            gvCurrentData.TopRowIndex = gvImportData.TopRowIndex;
        }

        private void gvCurrentData_TopRowChanged(object sender, EventArgs e)
        {
            gvImportData.TopRowIndex = gvCurrentData.TopRowIndex;
        }
    }
}
